package com.example.myproject.service;

import com.example.myproject.mapper.UserMapper;
import com.example.myproject.mapper.UserRatioDetailMapper;
import com.example.myproject.mapper.UserRatioLogMapper;
import com.example.myproject.model.User;
import com.example.myproject.model.UserRatio;
import com.example.myproject.model.UserRatioDetail;
import com.example.myproject.model.UserRatioLog;
import com.example.myproject.repository.UserRatioRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserRatioService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRatioRepository userRatioRepository;

    @Autowired
    private UserMoneyService userMoneyService;

    @Autowired
    private UserRatioLogMapper userRatioLogMapper;

    @Autowired
    private UserRatioDetailMapper userRatioDetailMapper;

    @Transactional
    public void updateUploadDownload(String passkey, long uploaded, long downloaded, String infohash) {
        System.out.println("进入了更新部分，其中passkey是：" + passkey);
        User user = userMapper.findByPasskey(passkey);
        if (user == null) {
            throw new RuntimeException("User not found for passkey: " + passkey);
        }

        Long userId = user.getUserId();
        System.out.println("userid:" + userId);

        //更新 user_ratio_detail
        UserRatioDetail detail = userRatioDetailMapper.findByUserIdAndInfohash(userId, infohash);
        if (detail == null) {
            detail = new UserRatioDetail();
            detail.setUserId(userId);
            detail.setInfohash(infohash);
            detail.setUpload(uploaded);
            detail.setDownload(downloaded);
            userRatioDetailMapper.insert(detail);
        } else {
            // 计算增量，防止数据回退
            long uploadDelta = uploaded - detail.getUpload();
            long downloadDelta = downloaded - detail.getDownload();
            if (uploadDelta < 0) uploadDelta = 0;
            if (downloadDelta < 0) downloadDelta = 0;

            detail.setUpload(detail.getUpload() + uploadDelta);
            detail.setDownload(detail.getDownload() + downloadDelta);
            userRatioDetailMapper.update(detail);
        }

        //更新ratio
        Long totalUpload = userRatioDetailMapper.sumUploadByUserId(userId);
        Long totalDownload = userRatioDetailMapper.sumDownloadByUserId(userId);

        if (totalUpload == null) totalUpload = 0L;
        if (totalDownload == null) totalDownload = 0L;

        UserRatio userRatio = userRatioRepository.findById(userId).orElse(null);
        if (userRatio == null) {
            userRatio = new UserRatio();
            userRatio.setUserId(userId);
        }
        userRatio.setUpload(totalUpload);
        userRatio.setDownload(totalDownload);
        userRatio.setRatio(calculateRatio(totalUpload, totalDownload));
        userRatioRepository.save(userRatio);

        //修改魔力值和经验
        //永远不会降低经验值
        long amount = (uploaded - downloaded) / 1000;
        if (amount > 0) {
            userMoneyService.reward(userId, amount, 0, amount);
        } else {
            userMoneyService.reward(userId, 0, 0, amount);
        }
        userRatioRepository.save(userRatio);

        //写入日志，便于统计变化
        UserRatioLog log = new UserRatioLog();
        log.setUserId(userId);
        log.setTime(LocalDateTime.now());
        log.setUpload(uploaded - detail.getUpload());
        log.setDownload(downloaded - detail.getDownload());
        userRatioLogMapper.insert(log);

        checkAndBanIfCheating(userId);
    }


    private double calculateRatio(long upload, long download) {
        if (download == 0) {
            return upload > 0 ? Double.MAX_VALUE : 0.0;
        }
        return (double) upload / download;
    }

    private void checkAndBanIfCheating(Long userId) {
        // 获取最近5次上传记录
        List<Long> recentUploads = userRatioLogMapper.findLastNUploads(userId, 5);
        if (recentUploads == null || recentUploads.size() < 5) return;

        // 检查是否全部相同且非0（刷上传）
        boolean allSame = recentUploads.stream().distinct().count() == 1;
        if (allSame && recentUploads.get(0) > 0) {
            userMapper.banUser(userId);
            System.out.println("封禁用户：" + userId + "，原因：5次上传值完全相同");
            return;
        }

        // 检查上传增量是否恒定（每次 +1000 也可疑）
        List<Long> deltas = new ArrayList<>();
        for (int i = 1; i < recentUploads.size(); i++) {
            deltas.add(recentUploads.get(i) - recentUploads.get(i - 1));
        }

        boolean allDeltaSame = deltas.stream().distinct().count() == 1;
        Long delta = deltas.get(0);
        if (allDeltaSame && delta > 0) {
            userMapper.banUser(userId);
            System.out.println("封禁用户：" + userId + "，原因：上传增量恒定：" + delta);
        }
    }

}